﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Wedo.Utility;
using System.Web.Mvc; 
using Wedo.Recognition.Domain; 
using System.Data.Entity;
using Wedo.Service.Common;
using Wedo.Domain.Models; 
using Wedo.Recognition.Repository;
using Wedo.Mvc.Pager;
using Wedo.Mvc.Utility;


namespace Wedo.Recognition.Service
{
    public class SysParamService : BaseService<SysParam>, IBaseService<SysParam>
    {
 
        #region 基础
        public SysParamService(IUnitWork dbContext)
            : base(dbContext, dbContext.CacheSet<SysParam>())
        {

        }

        /// <summary>
        /// 根据参数列表名称和值查找字符串
        /// </summary>
        /// <param name="paramListName">参数列表名称</param>
        /// <param name="paramValue">值</param>
        /// <returns>对应的字符串</returns>
        public string GetText(string parent, string paramValue)
        {
            if (paramValue.IsNullOrWhiteSpace())
                return "";
            var pListItem = _repository.Find(m => m.Id.StartsWith(parent)&&m.ParamValue== paramValue);
            if (pListItem != null)
                return pListItem.ParamText;
            return paramValue;
        }

        /// <summary>
        /// 根据参数列表名称和字符串查找值
        /// </summary>
        public string GetValue(string paramText, string parent)
        {
            int leng = (parent ?? "").Length + 3 ;
            var pListItem = _repository.Find(s => s.ParamText.Length == leng &&
                s.ParamText.StartsWith(parent)
                && s.ParamValue == paramText);

            if (pListItem != null)
                return pListItem.ParamValue;
            return string.Empty;
        }

        /// <summary>
        /// 根据参数名称获取列表
        /// </summary>
        /// <param name="paramListName">列表名称</param>
        /// <returns>下拉列表</returns>
        public IEnumerable<SelectListItem> GetList(string parent)
        {
            int leng = (parent ?? "").Length + 3;

            List<SelectListItem> list = new List<SelectListItem>();
            var pListItem = _repository.Find(s => s.ParamText.StartsWith(parent) 
                && s.ParamText.Length == leng);
 
            return list;
        }

        /// <summary>
        /// 由父类获取子类(未完成)
        /// </summary>
        /// <param name="parent">父类</param>
        /// <returns></returns>
        public List<SelectListItem> GetListByParent(string parent=null)
        {
            List<SelectListItem> list = new List<SelectListItem>() { new SelectListItem() { Value = "", Text = "", Selected = true } };
            IQueryable<SysParam> query = _repository.All();
            if (parent.IsNullOrWhiteSpace())
                query = query.Where(m => m.Id == null || m.Id.Length == 0);
            else{
                int length=parent.Length+3;
                query = query.Where(m => m.Id.StartsWith(parent) && m.Id.Length >= length);
            }
            return query.Select(s=>new SelectListItem { Text = s.ParamText, Value = s.ParamValue }).ToList();
        }

        /// <summary>
        /// GetName
        /// </summary>
        /// <param name="value"></param>
        /// <param name="parent"></param>
        /// <returns></returns>
        public string GetParamNameByValue(string value,string parent=null)
        {
            List<SelectListItem> list = new List<SelectListItem>();
            var pListItem = _repository.Filter(s => s.Id == parent && s.ParamValue == value).FirstOrDefault();
            if (pListItem == null)
                return "";
            else
                return pListItem.ParamText;

        }

        /// <summary>
        /// 获取一级列表
        /// </summary>
        /// <returns></returns>
        public List<SelectListItem> GetAllOneLevelList()
        {
            return _repository.Filter(s => s.Id == "" || s.Id == null)
                .Select(s => new SelectListItem { Text = s.ParamText, Value = s.ParamValue })
                .ToList() ;
        } 
        #endregion

        private string GetMaxCateID(string parent = null)
        {
            int length = (parent ?? "").Length + 3;
            string max = _repository.Filter(m => m.Id.StartsWith(parent) 
                && m.Id.Length == length).Max(m => m.Id);
            if (max.IsNullOrWhiteSpace())
            {
                return (parent ?? "") + "001";
            }
            int newMaxID = max.TryParseTo<int>().GetValueOrDefault(0) + 1;
            return newMaxID.ToString().PadLeft(length,'0');
        }

        public void Add(SysParam entity,string parent)
        {
            if (Check(entity))
                throw new Exception("已有此参数名");

            string cateid = GetMaxCateID(parent);

            entity.Id = cateid;
            Add(entity);
        }

        public override SysParam Update(SysParam entity)
        {
            if (Check(entity,entity.Id))
                throw new Exception("已有此参数名");

            var model = GetById(entity.Id);
            model.ParamText = entity.ParamText;
            model.ParamValue = entity.ParamValue; 

            Commit();
            return model;
        }
 
        private bool Check(SysParam entity,string ID=null)
        {
            if (entity == null)
                throw new Exception("没有此对象");
            if (entity.ParamText.IsNullOrWhiteSpace())
                throw new Exception("请填写参数名");
            if (entity.ParamValue.IsNullOrWhiteSpace())
                throw new Exception("请填写参数值");
            if(ID.IsNotNullOrWhiteSpace())
                return _repository.Filter(m => m.ParamText == entity.ParamText  && m.Id != ID)
                    .Count() > 0;
            else
                return _repository.Filter(m => m.ParamText == entity.ParamText )
                    .Count() > 0;
        }

        public PagedList<SysParam> ToPagedList(SearchModel where)
        {
            where = where ?? new SearchModel();
            IEnumerable<SysParam> query = _repository.All();
            if (where.Keyword.IsNotNullOrWhiteSpace())
            {
                query = query.Where(m => m.ParamValue.Contains(where.Keyword) || m.ParamText.Contains(where.Keyword));
            } 
            var list = query.OrderBy(m => m.Id).ToList();
            return new PagedList<SysParam>(list,where.Page, 10);
        }

        /// <summary>
        /// 下拉列表
        /// </summary>
        /// <param name="val"></param>
        /// <returns></returns>
        public List<SelectListItem> GetCategory(string val)
        {
            List<SelectListItem> selects = new List<SelectListItem>();
            var list= this._repository.All();
            foreach (var item in list)
            {
                int level = item.Level-1;
                string text = "".PadLeft(level*2,'—') +item.ParamText;
                selects.Add(new SelectListItem { Selected = val == item.Id, Text = text, Value = item.Id });
            }
            return selects;
        }
    }
}
